#include <QFileDialog>
#include <QDateTime>
#include <QDir>
#include <QSettings>

#include "photocopydialog.h"
#include "ui_photocopydialog.h"
#include "overwritedlg.h"


/*----------------------------------------------------------------------------*/
PhotoCopyDialog::PhotoCopyDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::PhotoCopyDialog)
{
    m_overwrite   = eNope;
    m_bCreateYear = false;
    m_nFile       = 1;
    m_nAllFiles   = 0;
    m_version     = e_LastVersion;

    ui->setupUi(this);
}

/*----------------------------------------------------------------------------*/
PhotoCopyDialog::~PhotoCopyDialog()
{
    delete ui;
}

/*----------------------------------------------------------------------------*/
void
PhotoCopyDialog::callChooseDirDialog(QLineEdit*& edit, QString caption)
{
    QString dir = QFileDialog::getExistingDirectory(
                this,
                caption,
                edit->text());

    if (!dir.isEmpty())
    {
        edit->setText(dir);
    }
}

/*----------------------------------------------------------------------------*/
void
PhotoCopyDialog::on_pushButtonFrom_clicked()
{
    callChooseDirDialog(ui->lineEditFrom, trUtf8("Каталог откуда копировать фотографии"));
    m_sFrom = ui->lineEditFrom->text();
}

/*----------------------------------------------------------------------------*/
void
PhotoCopyDialog::on_pushButtonTo_clicked()
{
    callChooseDirDialog(ui->lineEditTo, trUtf8("Каталог куда копировать фотографии"));
    m_sTo = ui->lineEditTo->text();
}

/*----------------------------------------------------------------------------*/
void
PhotoCopyDialog::on_pushButtonCopy_clicked()
{
    ui->pushButtonCopy->setDisabled(true);
        // get extensions
    QString     exts = ui->lineEditExtensions->text();
    m_slExtensions = exts.split(",");
        // get data from widgets
    m_bCreateYear = ui->checkBoxSplitYears->isChecked();
        // get date from
    if (m_bDateFrom)
        m_dateFrom = ui->dateEditFrom->dateTime();
        // get date to
    if (m_bDateTo)
    {
        m_dateTo = ui->dateEditTo->dateTime();
        m_dateTo.setTime(QTime(23, 59, 59, 99));
    }

    try
    {
        if (!m_sFrom.isEmpty() && !m_sTo.isEmpty())
        {
            if (m_sFrom.right(1)[0] != '/')
                m_sFrom += '/';
            if (m_sTo.right(1)[0] != '/')
                m_sTo += '/';

            m_nAllFiles = countFiles(m_sFrom);
            copy(m_sFrom);
        }
    }
    catch(int i)
    {
    }
    m_nFile = 1;
    m_nAllFiles = 0;
    m_overwrite = eNope;

    ui->pushButtonCopy->setDisabled(false);

    close();

}

//-----------------------------------------------------------------------------
unsigned
PhotoCopyDialog::countFiles(QString strDir)
{
    unsigned    counter = 0;

    if (strDir.right(1)[0] != '/')
        strDir += '/';

    QDir            dir(strDir);
    QFileInfoList   fil = dir.entryInfoList();
    QFileInfo       fi;

    foreach (fi, fil)
    {
        if (!fi.isDir())
        {
            if (m_slExtensions.contains(fi.suffix()) && isAppropriateFileDate(fi.lastModified()))
                counter++;
        }
        else
        {
            if (fi.fileName() != "." && fi.fileName() != "..")
                counter += countFiles(strDir + fi.fileName());
        }
    }
    return counter;
}

//-----------------------------------------------------------------------------
bool
PhotoCopyDialog::isAppropriateFileDate(const QDateTime& dt)
{
    if (m_bDateFrom && dt < m_dateFrom)
        return false;
    if (m_bDateTo   && dt > m_dateTo)
        return false;
    return true;
}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::copy(QString strDir)
{

    if (strDir.right(1)[0] != '/')
        strDir += '/';

    QDir            dir(strDir);
    QFileInfoList   fil = dir.entryInfoList();
    QFileInfo       fi;

    ui->progressBarFiles->setRange(0, m_nAllFiles);

    foreach (fi, fil)
    {
        if (!fi.isDir())
        {
            if (m_slExtensions.contains(fi.suffix()) && isAppropriateFileDate(fi.lastModified()))
                copyFile(strDir + fi.fileName(), fi.fileName(), fi);
        }
        else
        {
            if (fi.fileName() != "." && fi.fileName() != "..")
                copy(strDir + fi.fileName());
        }
        ui->progressBarFiles->setValue(m_nFile);
    }
}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::copyFile(const QString& fileNameIn, const QString& fileName, const QFileInfo& fileinfo)
{
    QString     dirOut;
    QString     m_folderFormat('_'); // choose from dialog
    QDir        dir;
    QDateTime   dt(fileinfo.lastModified());
    QDate       d = dt.date();
    QString     sDirYear;

    if (m_bCreateYear)
    {
        sDirYear = QString("%1%2").arg(m_sTo).arg((int)d.year(), 4, 10, QLatin1Char('0'));
        if (!dir.exists(sDirYear))
            dir.mkdir(sDirYear);
        sDirYear += '/';
    }
    else
        sDirYear = m_sTo;

    dirOut = QString("%1%2%3%4%3%5").
        arg(sDirYear).
        arg((int)d.year(), 4, 10, QLatin1Char('0')).
        arg(m_folderFormat).
        arg((int)d.month(), 2, 10, QLatin1Char('0')).
        arg((int)d.day(), 2, 10, QLatin1Char('0'));

    if (!dir.exists(dirOut))
        dir.mkdir(dirOut);

    dirOut += '/';

    QFile   fileFrom(fileNameIn);
    QFile   fileTo(dirOut + fileName);
    if (fileTo.exists())
    {
        if (m_overwrite == eYesAll)
        {
            fileTo.remove();
        }
        else if (m_overwrite == eNoAll)
        {
            m_nFile++;
            return;
        }
        else
        {
            OverwriteDlg        dlg;
            QFileInfo           fiNew(dirOut + fileName);
            dlg.setData(fileName, fileinfo, fiNew);
            dlg.exec();
            switch (dlg.getResult())
            {
            case eNope:
                throw (int)eNope;
            case eYesAll:
                m_overwrite = eYesAll;
            case eYes:
                fileTo.remove();
                break;
            case eNoAll:
                m_overwrite = eNoAll;
            case eNo:
                m_nFile++;
                return;
            }
        }
    }
    fileFrom.copy(dirOut + fileName);
    m_nFile++;
}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::showEvent(QShowEvent* event)
{
    readSettings();

    on_checkBoxFromDate_clicked();
    on_checkBoxToDate_clicked();

    QDialog::showEvent(event);
}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::readSettings()
{

    QSettings settings("Dms", "photocopy");

    // version
    m_version = (Versions)settings.value(QString("version"), (int)m_version).toInt();
    // from
    m_sFrom = settings.value(QString("from"), QString("")).toString();
    ui->lineEditFrom->setText(m_sFrom);
    // to
    m_sTo = settings.value(QString("to"), QString("")).toString();
    ui->lineEditTo->setText(m_sTo);
    // extensions
    ui->lineEditExtensions->setText(settings.value(QString("extensions"), QString("JPG")).toString());
    // split for years
    ui->checkBoxSplitYears->setChecked(settings.value(QString("extensions"), false).toBool());

    if (m_version > e_v1)
    {
        // date from check
        ui->checkBoxFromDate->setChecked(settings.value(QString("fromDateCheck"), false).toBool());
        // date from
        ui->dateEditFrom->setDateTime(settings.value(QString("fromDate"), QDateTime()).toDateTime());
        // date to check
        ui->checkBoxToDate->setChecked(settings.value(QString("toDateCheck"), false).toBool());
        // date to
        ui->dateEditTo->setDateTime(settings.value(QString("toDate"), QDateTime()).toDateTime());
    }
}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::closeEvent(QCloseEvent* e)
{

    writeSettings();

    QDialog::closeEvent(e);

}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::writeSettings()
{

    QSettings settings("Dms", "photocopy");

    // version
    settings.setValue("version", m_version);
    // from
    settings.setValue("from", m_sFrom);
    // to
    settings.setValue("to", m_sTo);
    // extensions
    settings.setValue("extensions", ui->lineEditExtensions->text());
    // split for years
    settings.setValue("splityears", ui->checkBoxSplitYears->isChecked());
    // date from check
    settings.setValue("fromDateCheck", ui->checkBoxFromDate->isChecked());
    // date from
    settings.setValue("fromDate",   ui->dateEditFrom->dateTime());
    // date to check
    settings.setValue("toDateCheck", ui->checkBoxToDate->isChecked());
    // date to
    settings.setValue("toDate",   ui->dateEditTo->dateTime());
}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::on_checkBoxFromDate_clicked()
{
    m_bDateFrom = ui->checkBoxFromDate->isChecked();
    ui->dateEditFrom->setEnabled(m_bDateFrom);
}

//-----------------------------------------------------------------------------
void
PhotoCopyDialog::on_checkBoxToDate_clicked()
{
    m_bDateTo = ui->checkBoxToDate->isChecked();
    ui->dateEditTo->setEnabled(m_bDateTo);
}
